// messageHandler.js
import { v4 as uuidv4 } from 'uuid';
import { ElMessage } from 'element-plus';
export const messageHandler = {

  
// 在 messageHandler.js 的 processStreamResponse 方法中：
async processStreamResponse(response, { updateMessage, updateTokenCount }) {

  if (!response || !response.body) {
    console.error('无效的响应:', response);
    return;
  }
  // 处理 response.body
  let finalContent = '';
  let reasoningContent = '';
  let isFinal = false;
  let previousFullContent = ''; // 记录完整历史内容
  let buffer = ''; // 用于累积数据块

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    const chunk = decoder.decode(value);
    buffer += chunk; // 累积数据块

    // 处理累积的数据块
    while (buffer.length >= 0) {
      const dataStart = buffer.indexOf('data: ');
      if (dataStart === -1) break; // 没有找到 'data: '，继续累积

      const dataEnd = buffer.indexOf('\n', dataStart);
      if (dataEnd === -1) break; // 没有找到换行符，继续累积

      const line = buffer.substring(dataStart, dataEnd);
      buffer = buffer.substring(dataEnd + 1); // 移除已处理的部分

      if (line.startsWith('data: ')) {
        const jsonStr = line.slice(6);
        try {
          const data = JSON.parse(jsonStr);
          if (data.result?.content) {
            const currentFullContent = data.result.content;
            const currentContent = currentFullContent.replace(previousFullContent, '');
            previousFullContent = currentFullContent; // 更新历史内容

            // 提取本次增量中的完整标签块（使用全局匹配）
            const reasoningMatches = currentContent.match(
              /\[reasoning\][\s\S]*?\[\/reasoning\]/g // 匹配跨行的完整标签块
            ) || [];
            const inferenceMatches = currentContent.match(
              /\[inference\][\s\S]*?\[\/inference\]/g
            ) || [];

            // 过滤空内容
            if (reasoningMatches.length === 0 && inferenceMatches.length === 0) {
              continue; // 无有效增量时跳过
            }

            // 提取内容（避免重复内容）
            const newReasoning = reasoningMatches
              .map(match => match.replace(/(\[reasoning\]|\[\/reasoning\])/g, '').trim())
              .filter(part => part !== ''); // 过滤空字符串

            const newInference = inferenceMatches
              .map(match => match.replace(/(\[inference\]|\[\/inference\])/g, '').trim())
              .filter(part => part !== '');

            // 累加内容（仅添加新内容）
            reasoningContent = newReasoning.join('\n');
            finalContent = newInference.join('\n');
            console.log('newReasoning:', newReasoning);
            console.log('newInference:', newInference);

            // 触发更新前检查是否真的有变化
            if (newReasoning.length > 0 || newInference.length > 0) {
              updateMessage({
                content: finalContent,
                reasoning: reasoningContent,
                loading: !isFinal,
                isStreaming: !isFinal // 新增：同步 isStreaming 状态
              });
            }
          }
          isFinal = data.result?.is_finished || false;
          if (data.result?.is_finished) {
            isFinal = true;
            updateMessage({
              loading: false,
              isStreaming: false // 流式结束时设为 false
            });
          }
        } catch (e) {
          console.error('解析失败:', e);
        }
      }
    }
  }
},
  formatMessage(role, content, isThinking = false) {
    const hasImage = content.includes('![') && content.includes('](data:image/');
    return {
      id: uuidv4(),
      role,
      content,
      markdown: content,
      reasoning: '', // 新增字段
      hasImage,
      loading: isThinking,
      type: role === 'assistant' ? (isThinking ? 'thinking' : 'normal') : 'normal',
    };
  },

async simulateStreamResponse(cleanedContent, reasoning, { updateMessage, duration = 100 }) {
  // 第一阶段：仅更新思考内容
  let reasoningIndex = 0;
  const reasoningInterval = setInterval(() => {
    if (reasoningIndex >= reasoning.length) {
      clearInterval(reasoningInterval);
      // 思考内容完成后，开始最终内容的流式显示
      return startContentStream();
    }
    const currentReasoning = reasoning.slice(0, reasoningIndex + 1);
    updateMessage({
      reasoning: currentReasoning,
      loading: true
    });
    reasoningIndex++;
  }, duration);

  // 第二阶段：更新最终内容
  function startContentStream() {
    let contentIndex = 0;
    const contentInterval = setInterval(() => {
      if (contentIndex >= cleanedContent.length) {
        clearInterval(contentInterval);
        updateMessage({
          content: cleanedContent,
          reasoning: reasoning,
          loading: false
        });
        return;
      }
      const currentContent = cleanedContent.slice(0, contentIndex + 1);
      updateMessage({
        content: currentContent,
        reasoning: reasoning, // 保留完整的思考内容
        loading: true
      });
      contentIndex++;
    }, duration);
  }
}

};